import React, { Component } from "react";
import {
  DatePicker,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Popconfirm,
  Select,
  Cascader,
  message
} from "antd";
import "./VipsList.less";
import {
  SearchOutlined,
  DeleteOutlined,
  PlusCircleOutlined,
  EditOutlined,
} from "@ant-design/icons";
import "moment/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";
import { queryVips, addVips, deleteVips, updatepass } from "../../api/vipList";

export default class VipList extends Component {
  constructor(props) {
    super();
    this.state = {
      addressArr: [],
      passid: "",
      visible: false,
      visibleUp: false,
      vips: {
        username: "",
        userpass: "",
        sex: "男",
        address: "",
      },
      upVips: {
        userpass: "",
        // userTwopass: "",
      },
      columns: [
        {
          key: "Id",
          title: "Id",
          dataIndex: "key",
          align: "center",
          render(text, record, index) {
            return <>{index + 1}</>;
          },
        },
        {
          key: "username",
          title: "用户名",
          dataIndex: "username",
          align: "center",
        },
        {
          key: "sex",
          title: "性别",
          dataIndex: "sex",
          align: "center",
        },

        {
          key: "address",
          title: "地址",
          dataIndex: "address",
          align: "center",
        },
        {
          key: "role",
          title: "权限",
          dataIndex: "role",
          align: "center",
          render(text, record, index) {
            return <>{record.roleType}</>;
          },
        },
        {
          key: "vipsHandle",
          title: "操作",
          dataIndex: "vipsHandle",
          align: "center",
          render: (text, record, index) => {
            return (
              <>
                <EditOutlined
                  style={{ margin: "0 5px", color: "#666" }}
                  onClick={() => this.showUpModal(record)}
                />
                <Popconfirm
                  title="亲，你确定要删除吗?"
                  onConfirm={() => this.deleteVips(record)}
                  okText="确认"
                  cancelText="取消"
                >
                  <DeleteOutlined style={{ color: "#666" }} />
                </Popconfirm>
              </>
            );
          },
        },
      ],
      data: [],
      // 省市级联
      options: [
        {
          value: "陕西省",
          label: "陕西省",
          children: [
            {
              value: "西安市",
              label: "西安市",
            },
            {
              value: "宝鸡市",
              label: "宝鸡市",
            },
            {
              value: "汉中市",
              label: "汉中市",
            },
            {
              value: "大荔市",
              label: "大荔市",
            },
            {
              value: "榆林市",
              label: "榆林市",
            },
          ],
        },
        {
          value: "山西省",
          label: "山西省",
          children: [
            {
              value: "吕梁市",
              label: "吕梁市",
            },
            {
              value: "运城市",
              label: "运城市",
            },
            {
              value: "临汾市",
              label: "临汾市",
            },
            {
              value: "大同市",
              label: "大同市",
            },
            {
              value: "晋中市",
              label: "晋中市",
            },
          ],
        },
      ],
    };
  }

  // 获取会员列表,state中定义一个空数组，用来接收后端传来的数据
  getVipsList() {
    // console.log("获取会员列表");
    queryVips().then((res) => {
      // console.log(res);
      let vipsArr = res.data;
      vipsArr.forEach((item) => {
        item.key = item._id;
      });
      this.setState({
        data: [...vipsArr],
      });
    });
  }
  componentDidMount() {
    this.getVipsList();
  }

  // 删除按钮
  deleteVips(record) {
    // 做权限判断
    if(record.roleType>1){
      // console.log(record); //点击删除行的所有信息{_id: "5fab84a46e2a464a683dc9de", username: "17609515527", userpass: "1234657", sex: "男", address: "山西省运城市", …}
    deleteVips({ _id: record._id }).then((res) => {
      //根据传给后端的id进行删除
      console.log(res); //{state: "删除成功"}
      if (res.state === "删除成功") {
        this.getVipsList();
      }
    });
    }else{
      message.warning('权限不足');
    }
  }

  // 显示添加弹窗 再次打开时置空
  showAddModal = () => {
    this.setState({
      addressArr: [],
      vips: {
        username: "",
        userpass: "",
        sex: "男",
        address: "",
      },
      visible: true,
    });
  };
  // 保存添加弹窗 连接接口传入参数并更新数据
  handleOk = (e) => {
    // console.log(e);
    addVips(this.state.vips).then((res) => {
      console.log(res); //{state: "添加成功"}
      if (res.state === "添加成功") {
        this.getVipsList();
      }
      this.setState({
        visible: false,
      });
    });
  };
  // 双向绑定 事件源,属性名
  changeValAdd(e, key) {
    this.setState({
      vips: {
        ...this.state.vips,
        [key]: e.target.value,
      },
    });
  }
  // 性别
  handleChange(value) {
    console.log(value.label); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
    this.setState({
      vips: {
        ...this.state.vips,
        sex: value.label,
      },
    });
  }
  // 省市级联
  onChangeProvCity(value) {
    // console.log(typeof  JSON.stringify(value) );//str
    // console.log( value);
    // console.log( str.substring(2,5),str.substring(8,11) );()
    console.log(value);
    let str = value.join("");
    console.log(value, 1);
    console.log(str);
    this.setState({
      addressArr: value,
      vips: {
        ...this.state.vips,
        address: str,
      },
    });
  }
  // 取消添加弹窗
  handleCancel = (e) => {
    // console.log(e);
    this.setState({
      visible: false,
    });
  };

  // 显示编辑弹窗
  showUpModal = (record) => {
    console.log(record); //当前行所有信息
    if(record.roleType>1){
      this.setState({
        visibleUp: true,
        passid: record._id,
        upVips: {
          userpass: "",
          // userTwopass: "",
        },
      });
    }else{
      message.warning('权限不足');
    }
    
  };
  // 保存编辑弹窗
  handleOkUp = () => {
    console.log(this.state.passid, this.state.upVips.userpass);
    updatepass({
      _id: this.state.passid,
      userpass: this.state.upVips.userpass,
    }).then((res) => {
      console.log(res);
      if (res.state === "修改成功") {
        this.getVipsList();
      }
    });
    this.setState({
      visibleUp: false,
    });
  };
  // 修改双向绑定
  changeValUp(e, key) {
    this.setState({
      upVips: {
        ...this.state.upVips,
        [key]: e.target.value,
      },
    });
  }
  // 取消编辑弹窗
  handleCancelUp = (e) => {
    this.setState({
      visibleUp: false,
    });
  };

  render() {
    return (
      <div className="vipsList">
        <div className="searchBox">
          <div className="startDay">
            <span className="dayRange">日期范围</span>
            <DatePicker
              locale={locale}
              allowClear={true}
              placeholder="开始日"
              showToday={false}
              style={{ width: "185px", height: "38px" }}
            />
          </div>
          <DatePicker
            locale={locale}
            allowClear={true}
            placeholder="截止日"
            showToday={false}
            style={{ width: "185px", height: "38px" }}
          />
          <div className="searchTxt">
            <input type="text" placeholder="请输入用户名" />
          </div>
          <Button
            className="searchBtn"
            type="default"
            icon={<SearchOutlined />}
          ></Button>
        </div>
        <div className="btnBox">
          <div className="btnBoxSelect">
            <Button
              className="addBtn"
              type="default"
              icon={<PlusCircleOutlined />}
              onClick={this.showAddModal}
            >
              添加
            </Button>
          </div>
          <div className="numTotal">
            <span>共有数据：</span>
            <span className="numTotal-num">{this.state.data.length}</span>
            <span>条</span>
          </div>
        </div>
        <div className="tableCon">
          <Table
            // rowSelection={{
            //   type: "checkbox",
            // }}
            bordered
            columns={this.state.columns}
            dataSource={this.state.data}
          />
          {/* 添加会员弹窗 */}
          <Modal
            title="添加用户"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            cancelText="取消"
            okText="保存"
            centered
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
            >
              <Form.Item label="用户名" required="true">
                <Input
                  value={this.state.vips.username}
                  onChange={(e, key) => this.changeValAdd(e, "username")}
                />
              </Form.Item>
              <Form.Item label="密码" required="true">
                <Input
                  type="password"
                  value={this.state.vips.userpass}
                  onChange={(e, key) => this.changeValAdd(e, "userpass")}
                />
              </Form.Item>
              <Form.Item label="性别" required="true">
                <Select
                  labelInValue
                  defaultValue={{ value: "男" }}
                  onChange={(value) => this.handleChange(value)}
                >
                  <Select.Option value="男">男</Select.Option>
                  <Select.Option value="女">女</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="地址" required="true">
                <Cascader
                  options={this.state.options}
                  onChange={(value) => this.onChangeProvCity(value)}
                  value={this.state.addressArr}
                  placeholder="===请选择==="
                />
              </Form.Item>
            </Form>
          </Modal>
          {/* 编辑会员弹窗 */}
          <Modal
            title="编辑"
            visible={this.state.visibleUp}
            onOk={this.handleOkUp}
            onCancel={this.handleCancelUp}
            cancelText="取消"
            okText="保存"
            centered
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
            >
              <Form.Item label="原密码" required="true">
                <Input type="password" value="*********" disabled />
              </Form.Item>
              <Form.Item label="新密码" required="true">
                <Input
                  type="password"
                  value={this.state.upVips.userpass}
                  onChange={(e) => this.changeValUp(e, "userpass")}
                />
              </Form.Item>
              {/* <Form.Item label="确认密码" required="true">
                <Input
                  type="password"
                  value={this.state.upVips.userTwopass}
                  onChange={(e) => this.changeValUp(e, "userTwopass")}
                />
              </Form.Item> */}
            </Form>
          </Modal>
        </div>
      </div>
    );
  }
}
